package com.zhiqianbao.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.zhiqianbao.R;
import com.zhiqianbao.adapter.NiceSpinner;
import com.zhiqianbao.entity.ContaciInfo;
import com.zhiqianbao.entity.PhoneContact;
import com.zhiqianbao.shared.SharedPreferanceUtils;
import com.zhiqianbao.utils.Constants;
import com.zhiqianbao.utils.HttpUtils;
import com.zhiqianbao.utils.WorthPurseUtil;

import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import cn.trinea.android.common.util.StringUtils;

/**
 * Created by 子龙 on 2017/4/24.
 * 添加联系人页面
 */

public class AddContactsInfo2Activity extends BaseActivity implements View.OnClickListener {
    public static final int CHECKRELATION=0x123;
    public static final int AddUserContacts=0x124;
    private Gson gson = new Gson();
    private Button bt_true;
    private TextView topbar_textview_title;
    private ImageView iv_relative1;
    private EditText edit_second_contactName;
    private EditText put_phone2;
    private NiceSpinner marry_yes3;
    private String selectText;
    private Button button_return;
    private SharedPreferanceUtils sharedPreferanceUtils;
    List<String> dataset;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.addcontactperson_activity);
        initView();
        initData();
        addListner();
    }

    private void initData() {
        marry_yes3.setTextColor(Color.GRAY);
        dataset = new LinkedList<>(Arrays.asList("母亲", "父亲","子女", "兄弟", "姐妹", "其他亲属 ", "朋友", "同事"));
        marry_yes3.attachDataSource(dataset);

        String marriger = getIntent().getExtras().getString("Marriger");
        String relationshape = getIntent().getExtras().getString("relationshape");
        if (!TextUtils.isEmpty(relationshape)&&relationshape.length()>0){
             String[] strings = relationshape.split(",");
            if (strings.length==1){
                if (dataset.contains(strings[0])){
                    dataset.remove(strings[0]);
                }
            }else if (strings.length==2){
                if (dataset.contains(strings[0])){
                    dataset.remove(strings[0]);
                }
                if (dataset.contains(strings[1])){
                    dataset.remove(strings[1]);
                }
            }
        }

        marry_yes3.attachDataSource(dataset);


    }

    private void addListner() {
        bt_true.setOnClickListener(this);
        iv_relative1.setOnClickListener(this);
        button_return.setOnClickListener(this);
    }

    private void initView() {
        sharedPreferanceUtils = new SharedPreferanceUtils(this);
        bt_true = (Button) findViewById(R.id.bt_true);
        topbar_textview_title = (TextView) findViewById(R.id.topbar_textview_title);
        topbar_textview_title.setText("添加联系人");
        iv_relative1 = (ImageView)findViewById(R.id.iv_relative1);
        //联系人
        edit_second_contactName = (EditText) findViewById(R.id.edit_second_contactName);
        //填写手机号码
        put_phone2 = (EditText) findViewById(R.id.put_phone2);
        marry_yes3 = (NiceSpinner) findViewById(R.id.marry_yes3);
        selectText = marry_yes3.getText().toString().trim();
        button_return = (Button) findViewById(R.id.button_return);
    }


    @Override
    public void onClick(View v) {
        if(R.id.iv_relative1==v.getId()) {
                //输入联系人
                Intent contactsMobileIntent2 = new Intent(AddContactsInfo2Activity.this, ContactsMobileActivity.class);
                contactsMobileIntent2.putExtra("edit", "0");
                startActivityForResult(contactsMobileIntent2, 2);
        }
        else if(R.id.bt_true==v.getId()){
            //确认
            if (StringUtils.isBlank(edit_second_contactName.getText().toString())
                    || StringUtils.isBlank(put_phone2.getText().toString())
                    || StringUtils.isBlank(marry_yes3.getText().toString().trim())) {
                showShortToast1("信息没有填完整");
                return;
            }
            if (marry_yes3.getText().toString().trim().equals("配偶")) {
                getDataFromServer();
            } else {
                getAllPerson();
            }

        }
        else if(R.id.button_return==v.getId()) {
                finish();
        }
    }

    private void getDataFromServer() {
        if(Constants.LOGIN_USER==null){
            Intent loginIntent = new Intent(AddContactsInfo2Activity.this, WorthPurseUtil.getZhiddActivity().getClass());
            startActivity(loginIntent);
            finish();
        }
        else {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Message message = new Message();
                    Map<String, String> mapParams = new HashMap<>();
                    mapParams.put("userId", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getId() + "" : "");
                    mapParams.put("token", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getToken() : "");
                    String result = HttpUtils.httpPostString(Constants.API_ROOT + "/user/auth/checkRelation",
                            mapParams, AddContactsInfo2Activity.this);
                    if (StringUtils.isBlank(result)) {
                        message.what = RESULT_CANCELED;
                    } else {
                        message.what = CHECKRELATION;
                        ContaciInfo data =gson.fromJson(result, ContaciInfo.class);
                        message.obj = data;
                    }
                    postHandler.sendMessage(message);
                }
            }).start();
        }

    }

    private void getAllPerson() {
        if(Constants.LOGIN_USER==null){
            Intent loginIntent = new Intent(AddContactsInfo2Activity.this,WorthPurseUtil.getZhiddActivity().getClass());
            startActivity(loginIntent);
            finish();
        }
        else {
            final String et_contacName = edit_second_contactName.getText().toString();
            final String tel = put_phone2.getText().toString();
            final String relation = marry_yes3.getText().toString().trim();
            showWaitDialog();

            new Thread(new Runnable() {
                @Override
                public void run() {
                    Message message = new Message();
                    Map<String, String> mapParams = new HashMap<>();
                    mapParams.put("userId", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getId() + "" : "");
                    mapParams.put("token", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getToken() : "");
                    mapParams.put("phone", tel);
                    mapParams.put("relation", relation);
                    mapParams.put("name", et_contacName);
                    String result = HttpUtils.httpPostString(Constants.API_ROOT + "/user/addUserContacts",
                            mapParams, AddContactsInfo2Activity.this);
                    if (StringUtils.isBlank(result)) {
                        message.what = RESULT_CANCELED;
                    } else {
                        message.what = AddUserContacts;
                        ContaciInfo data =gson.fromJson(result, ContaciInfo.class);
                        message.obj = data;
                    }
                    postHandler.sendMessage(message);
                }
            }).start();

        }

    };

    Handler postHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case RESULT_CANCELED:
                    showShortToast1(Constants.HTTP_ERROR_MESSAGE);
                    break;
                case CHECKRELATION:
                    ContaciInfo response = (ContaciInfo) msg.obj;
                    if (response != null) {
                        //关系正确
                        if (response.getCode().equals("0")) {
                            showShortToast1(response.getMsg());
                            getAllPerson();

                            //关系错误
                        } else if (response.getCode().equals("1")) {
                            showShortToast1(response.getMsg());

                        } else if (response.getCode().equals("9")) {
                            Intent intent = new Intent(AddContactsInfo2Activity.this,
                                    WorthPurseUtil.getZhiddActivity().getClass());
                            intent.addFlags(intent.FLAG_ACTIVITY_CLEAR_TOP);
                            startActivity(intent);
                            showShortToast1("您的账号在其他设备登录,请重新登录");
                            finish();
                        }
                    }

                    break;
                case AddUserContacts:
                    closeWaitDialog();
                    ContaciInfo contaciInfo = (ContaciInfo) msg.obj;
                    if (contaciInfo != null) {
                        if (contaciInfo.getCode().equals("0")) {

                            showShortToast1(contaciInfo.getMsg());
                            //设置返回数据
//                        AddContactsInfo2Activity.this.setResult(RESULT_OK, intent);
                            setResult(RESULT_OK);
                            //关闭Activity
                            AddContactsInfo2Activity.this.finish();
                        } else {
                            showShortToast1(contaciInfo.getMsg());
                        }
                    }
                    break;
            }

        }
    };
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode){
            case 2:
                PhoneContact phoneContact1 = (PhoneContact) data.getSerializableExtra("phone");
                edit_second_contactName.setText(phoneContact1.getDesplayName());
                put_phone2.setText(phoneContact1.getPhoneNum());
                break;
        }
    }
}
